// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { InviteInfo, NoticeLeaveInvite, NoticeUserInviteStatus } from "../bean/GameBean";
import { GlobalBean } from "../bean/GlobalBean";
import { GameMgr } from "../common/GameMgr";
import SeatItemController from "../pfb/SeatItemController";
import { Config } from "../util/Config";
import { Tools } from "../util/Tools";

const { ccclass, property } = cc._decorator;


enum ButtonStyle {
    StartGray = 1,
    StartGreen = 2,
    Ready = 3,
    Cancel = 4,
}

@ccclass
export default class HallCreateRoomController extends cc.Component {

    @property(cc.Node)
    boardTab: cc.Node = null;
    @property(cc.Node)
    boardBgInner: cc.Node = null;
    @property(cc.Node)
    seatLayout: cc.Node = null;
    @property(cc.Node)
    seatTwoLayout: cc.Node = null;  //第二排的座位
    @property(cc.Node)
    buttonNoClick: cc.Node = null;   //灰色的 start 按钮
    @property(cc.Node)
    buttonStart: cc.Node = null;  //可点击的 start 按钮
    @property(cc.Node)
    buttonReady: cc.Node = null; //准备按钮
    @property(cc.Node)
    buttonCancel: cc.Node = null;  // 取消按钮
    @property(cc.Prefab)
    setaItemPfb: cc.Prefab = null;


    btnCopyNormal: cc.Node = null  //copy按钮  
    btnCopyLabel: cc.Node = null  //copy按钮文案   
    roomNumber: cc.Label = null  //房间号   
    ticketNumber: cc.Label = null  //门票价格 

    private seatCallback: Function
    private startCallBack: Function
    private readyCallBack: Function
    private cancelCallBack: Function

    countdownTimeLabel: cc.Label = null
    countdownInterval: number = null;//倒计时的 id
    seconds: number = 10;//倒计时 10 秒

    private _seatListCol: SeatItemController[] = []; //显示用户布局controller

    onLoad() {
        this.btnCopyNormal = this.boardTab.getChildByName('btn_copy_normal')
        this.btnCopyLabel = this.btnCopyNormal.getChildByName('label')
        this.roomNumber = this.boardTab.getChildByName('label').getComponent(cc.Label)
        this.ticketNumber = this.boardBgInner.getChildByName('ticket_number').getComponent(cc.Label)
        this.countdownTimeLabel = this.buttonReady.getChildByName('buttonLabel_time').getComponent(cc.Label)

    }
    protected onEnable(): void {
        this.scheduleOnce(() => {
            this.updateCountdownLabel(this.seconds);
            this.setFixedCountdownPosition()
            this.refreshData(GlobalBean.GetInstance().inviteInfo)
        })
    }

    start() {

        Tools.grayButton(this.buttonNoClick, () => { })

        Tools.greenButton(this.buttonStart, () => {
            if (this.startCallBack) {
                this.startCallBack()
            }
        })
        Tools.scaleButtonClick(this.buttonReady, () => {
            if (this.readyCallBack) {
                this.readyCallBack()
            }
        })

        Tools.redButton(this.buttonCancel, () => {
            if (this.cancelCallBack) {
                this.cancelCallBack()
            }
        })

        //copy 按钮的点击事件
        Tools.setTouchEvent(this.btnCopyNormal, (node: cc.Node) => {
            Tools.setNodeSpriteFrame(node, Config.hallRes + 'btn_copy_pressed');
            let color = cc.Color.fromHEX(new cc.Color(), '#925333');
            this.btnCopyLabel.color = color;
            this.btnCopyLabel.getComponent(cc.Label).fontSize = 26;
            Tools.copyToClipboard(this.roomNumber.string);
        }, (node: cc.Node) => {
            Tools.setNodeSpriteFrame(node, Config.hallRes + 'btn_copy_normal');
            let color = cc.Color.fromHEX(new cc.Color(), '#D07649');
            this.btnCopyLabel.color = color;
            this.btnCopyLabel.getComponent(cc.Label).fontSize = 28;
        }, (node: cc.Node) => {
            Tools.setNodeSpriteFrame(node, Config.hallRes + 'btn_copy_normal');
            let color = cc.Color.fromHEX(new cc.Color(), '#D07649');
            this.btnCopyLabel.color = color;
            this.btnCopyLabel.getComponent(cc.Label).fontSize = 28;
        });

    }

    //刷新数据
    refreshData(inviteInfo: InviteInfo) {

        if (inviteInfo == null) {
            return;
        }

        //这里是门票价格的赋值
        let fees = inviteInfo.fee;
        this.ticketNumber.string = fees === 0 ? window.getLocalizedStr('free') : fees + '';


        this._seatListCol = []
        this.refreshPlayer(inviteInfo)
        this.roomNumber.string = inviteInfo.inviteCode + '' //邀请码


        //初始进来就两种状态 房主是准备开始按钮  玩家是 ready 按钮
        if (inviteInfo.creatorId === GlobalBean.GetInstance().loginData.userInfo.userId) {//判断自己是不是房主
            this.btnCopyNormal.active = true;
        } else {
            this.btnCopyNormal.active = false;
        }

    }


    //刷新座位玩家
    refreshPlayer(inviteInfo: InviteInfo) {
        let peopleNumber: number = inviteInfo.playerNum;
        if (this._seatListCol.length < 1) {
            this.seatLayout.removeAllChildren();
            this.seatTwoLayout.removeAllChildren();

            if (peopleNumber <= 4) {
                this.schedule(() => {
                    this.seatLayout.setPosition(this.seatLayout.x, -90);
                }, 0)
                this.seatTwoLayout.active = false
                for (let i = 0; i < peopleNumber; i++) {
                    const item = cc.instantiate(this.setaItemPfb)
                    let seatEmptyItemController = item.getComponent(SeatItemController)
                    this._seatListCol.push(seatEmptyItemController)
                    this.seatLayout.addChild(item);
                    // 设置踢人回调，不再需要整个item的点击事件
                    seatEmptyItemController.setKickCallback((userId: string, nickname: string) => {
                        this.setSetaItemClick(userId, nickname);
                    });
                }
            } else {
                this.schedule(() => {
                    this.seatLayout.setPosition(this.seatLayout.x, -10);
                }, 0)
                this.seatTwoLayout.active = true
                for (let i = 0; i < 3; i++) {
                    const item = cc.instantiate(this.setaItemPfb)
                    let seatEmptyItemController = item.getComponent(SeatItemController)
                    this._seatListCol.push(seatEmptyItemController)
                    this.seatLayout.addChild(item);
                    // 设置踢人回调，不再需要整个item的点击事件
                    seatEmptyItemController.setKickCallback((userId: string, nickname: string) => {
                        this.setSetaItemClick(userId, nickname);
                    });
                }
                for (let i = 0; i < peopleNumber - 3; i++) {
                    const item = cc.instantiate(this.setaItemPfb)
                    let seatEmptyItemController = item.getComponent(SeatItemController)
                    this._seatListCol.push(seatEmptyItemController)
                    this.seatTwoLayout.addChild(item);
                    // 设置踢人回调，不再需要整个item的点击事件
                    seatEmptyItemController.setKickCallback((userId: string, nickname: string) => {
                        this.setSetaItemClick(userId, nickname);
                    });
                }
            }
        }

        for (let i = 0; i < this._seatListCol.length; i++) {
            if (i < inviteInfo.users.length) {
                this._seatListCol[i].setData(inviteInfo.users[i])
            } else {
                this._seatListCol[i].setData(null)
            }
        }

        if (GlobalBean.GetInstance().inviteInfo.creatorId === GlobalBean.GetInstance().loginData.userInfo.userId) {//判断自己是不是房主
            const readyCount = GlobalBean.GetInstance().inviteInfo.users.filter(user => user.ready).length;//查找准备好的玩家数量
            if (GlobalBean.GetInstance().inviteInfo.playerNum === readyCount) {//准备好的玩家数量和总玩家数量一致的话就可以开始游戏了
                this.setButtonType(ButtonStyle.StartGreen)
            } else {
                this.setButtonType(ButtonStyle.StartGray)
            }
        } else {
            const index = GlobalBean.GetInstance().inviteInfo.users.findIndex((item) => item.userId === GlobalBean.GetInstance().loginData.userInfo.userId);//搜索
            if (GlobalBean.GetInstance().inviteInfo.users[index].ready) {
                this.setButtonType(ButtonStyle.Cancel)
            } else {
                this.setButtonType(ButtonStyle.Ready)
                this.startCountdown(this.seconds)
            }
        }

    }

    protected onDisable(): void {
        setTimeout(() => {
            // this.ticketNumber.string = ''
            this.roomNumber.string = ''
            this.seatLayout.removeAllChildren()
            this.seatTwoLayout.removeAllChildren()
        }, 100);

        if (this.countdownInterval) {
            clearInterval(this.countdownInterval);
            this.countdownInterval = null
        }
    }

    //设置按钮显示状态
    setButtonType(buttonStyle: ButtonStyle) {
        this.buttonNoClick.active = false;
        this.buttonStart.active = false;
        this.buttonReady.active = false;
        this.buttonCancel.active = false;

        switch (buttonStyle) {
            case ButtonStyle.StartGray:
                this.buttonNoClick.active = true;
                break;
            case ButtonStyle.StartGreen:
                this.buttonStart.active = true;
                break;
            case ButtonStyle.Ready:
                this.buttonReady.active = true;
                break;
            case ButtonStyle.Cancel:
                this.buttonCancel.active = true;
                break;
        }
    }

    //启动倒计时
    startCountdown(seconds: number) {

        if (this.countdownInterval) {
            // GameMgr.Console.Error('当前存在的定时器 先销毁id：'+this.countdownInterval)
            clearInterval(this.countdownInterval);
            this.countdownInterval = null
        }

        // 在开始倒计时前确保位置正确
        this.setFixedCountdownPosition();
        let remainingSeconds = seconds;
        this.updateCountdownLabel(remainingSeconds);

        this.countdownInterval = setInterval(() => {
            remainingSeconds--;

            if (remainingSeconds <= 0) {
                // GameMgr.Console.Error('自动销毁的定时器 id：'+this.countdownInterval)
                clearInterval(this.countdownInterval);
                this.countdownInterval = null
                // 倒计时结束时的处理逻辑
                if (this.readyCallBack) {
                    this.readyCallBack()
                }
                return
            }
            // GameMgr.Console.Error('执行的定时器 id：'+this.countdownInterval)
            this.updateCountdownLabel(remainingSeconds);
        }, 1000);
        // GameMgr.Console.Error('创建的定时器 id：'+this.countdownInterval)
    }

    updateCountdownLabel(seconds: number) {
        if (this.countdownTimeLabel) {
            this.countdownTimeLabel.string = `（${seconds}s）`;
            // 每次更新倒计时文本后，重新设置位置，确保位置始终正确
            this.scheduleOnce(() => {
                this.setFixedCountdownPosition();
            }, 0.01);
        }
    }

    // 设置固定的倒计时位置，左括号始终对准ready文字的右边
    private setFixedCountdownPosition() {
        if (!this.buttonReady) {
            console.warn("HallCreateRoomController: setFixedCountdownPosition - buttonReady不存在");
            return;
        }

        // 重新获取节点，确保引用是最新的
        let btn = this.buttonReady.getChildByName('button_label');
        let timeBtn = this.buttonReady.getChildByName('buttonLabel_time');

        if (!btn || !timeBtn) {
            console.warn("HallCreateRoomController: setFixedCountdownPosition - 缺少子节点", {
                hasBtn: !!btn,
                hasTimeBtn: !!timeBtn
            });
            return;
        }

        // 重新获取倒计时标签组件，确保引用正确
        this.countdownTimeLabel = timeBtn.getComponent(cc.Label);
        if (!this.countdownTimeLabel) {
            console.warn("HallCreateRoomController: setFixedCountdownPosition - 无法获取Label组件");
            return;
        }

        // 延迟一帧执行，确保所有UI初始化完成
        this.scheduleOnce(() => {
            // 强制设置锚点为左对齐，确保左括号位置固定
            timeBtn.anchorX = 0;
            timeBtn.anchorY = 0.5; // 确保垂直居中
            // 注意：不要在这里强制修改倒计时标签的颜色，
            // 避免在倒计时文本更新时覆盖按钮按压（变暗）效果。

            // 计算固定位置：完全按照CongratsDialogController的实现，使用-10像素偏移
            let fixedLeftPos = btn.position.x + btn.width / 2 - 10; // 与CongratsDialogController完全一致

            // 直接设置位置
            timeBtn.setPosition(fixedLeftPos, 0);

            // 再次强制设置锚点，防止被其他代码重置
            timeBtn.anchorX = 0;
            timeBtn.anchorY = 0.5;

            console.log("HallCreateRoomController: 倒计时位置已设置为紧贴位置", {
                btnPos: btn.position,
                btnWidth: btn.width,
                fixedLeftPos: fixedLeftPos,
                timeBtnPos: timeBtn.position
            });

        }, 0.01);
    }

    //有玩家离开
    leavePlayer(noticeLeaveInvite: NoticeLeaveInvite) {
        GlobalBean.GetInstance().inviteInfo.users = GlobalBean.GetInstance().inviteInfo.users.filter(user => user.userId !== noticeLeaveInvite.userId);
        this.refreshPlayer(GlobalBean.GetInstance().inviteInfo);
    }

    //准备 取消准备
    setReadyState(noticeUserInviteStatus: NoticeUserInviteStatus) {
        if (GlobalBean.GetInstance().inviteInfo == null || GlobalBean.GetInstance().loginData == null) {
            return
        }

        GlobalBean.GetInstance().inviteInfo.users.forEach(user => {
            if (user.userId === noticeUserInviteStatus.userId) {
                user.ready = noticeUserInviteStatus.ready;
            }
        });
        this.refreshPlayer(GlobalBean.GetInstance().inviteInfo)
    }


    //设置 item 的点击事件
    setSetaItemClick(userId: string, nickname: string) {

        //得先判断当前的房间我是不是房主  并且要提出的不是我自己
        if (GlobalBean.GetInstance().inviteInfo.creatorId === GlobalBean.GetInstance().loginData.userInfo.userId
            && userId != GlobalBean.GetInstance().loginData.userInfo.userId
        ) {
            if (this.seatCallback) {
                this.seatCallback(userId, nickname)
            }
        }

    }

    //设置点击的回调
    setClick(seatCallback: Function, startCallBack: Function, readyCallBack: Function, cancelCallBack: Function) {
        this.seatCallback = seatCallback;
        this.startCallBack = startCallBack;
        this.readyCallBack = readyCallBack;
        this.cancelCallBack = cancelCallBack;

    }

    // update (dt) {}
}
